package com.huisou.basedataservice;

import com.huisou.domain.AskCategory;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class AskCategoryDao {
	
	protected Logger		log	= LoggerFactory.getLogger(getClass());
	
	private JdbcTemplate	jt;
	
	@Resource(name = "askDataSource")
	public void setDs(DataSource ds) {
		jt = new JdbcTemplate(ds);
	}
	
	@Resource
	private StringRedisTemplate	stringRedisTemplate;
	
	/**
	 * @param parentId
	 * @return
	 */
	public String getNameById(Integer id) {
		String key = RedisConstants.KEY_ASKCATEGORY_SIGNLE_NAME + "_" + id;
		
		String askCategoryName = null;
		
		try {
			askCategoryName = stringRedisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("获取生意经类别出错:" + e.getMessage());
		}
		
		if (StringUtils.isBlank(askCategoryName)) {
			try {
				askCategoryName = jt.queryForObject("select id ,code ,name from ask_cats where id = ? ", new Object[] { id }, new RowMapper<AskCategory>() {
					public AskCategory mapRow(ResultSet rs, int rowNum) throws SQLException {
						AskCategory ac = new AskCategory();
						ac.setId(rs.getInt("id"));
						ac.setName(rs.getString("name"));
						return ac;
					}
				}).getName();
				if (StringUtils.isNotBlank(askCategoryName)) {
					stringRedisTemplate.opsForValue().set(key, askCategoryName);
				}
			}
			catch (Exception e) {
				log.error("获取生意经类别出错:" + e.getMessage());
				return null;
			}
		}
		return askCategoryName;
	}
	
}
